<?php

namespace app\api\controller;

use app\api\model\ArtCollect;
use app\api\model\Article;
use app\api\model\Comment;
use app\api\model\Follow;
use app\api\model\User;
use app\api\validate\User as ValidateUser;
use app\common\LogService;
use app\common\model\ScoreLog;
use think\exception\ValidateException;
use think\facade\Db;
use think\Validate;

class Account extends Base
{
    public function index()
    {
        $user = User::where(['id' =>  $this->uid])
            ->field('id,qq,nickname,score,exp,role,signature,avator,last_login_ip,last_time,create_time')
            ->find();
        $user['art'] = Article::where(['user_id' => $this->uid])->count();
        $user['comment'] = Comment::where(['user_id' => $this->uid])->count();
        $user['collect'] = ArtCollect::where(['user_id' => $this->uid])->count();
        $user['follow'] = Db::name('follow')->where(['user_id' => $this->uid, 'relation_type' => 1, 'delete_time' => 0])->count();
        $user['fans'] = Db::name('follow')->where(['follow_id' => $this->uid, 'relation_type' => 1, 'delete_time' => 0])->count();
        $user['is_vip'] = User::checkVip($this->uid);
        return success($user);
    }

    public function edit()
    {
        $param = input();
        $recordLog = function ($status, $message = '') {
            LogService::record(
                name: '用户信息修改',
                user_id: $this->uid,
                status: $status,
                content: $message == '' ? [] : $message,
            );
        };
        try {
            $data = [];
            $user = User::where(['id' =>  $this->uid])->find();
            if (isset($param['signature']) && $param['signature'] != "" && $user['signature'] != $param['signature']) {
                $data['signature'] = $param['signature'];
            } 
            if (isset($param['nickname']) && $param['nickname'] != ""  && $param['nickname'] != $user['nickname']) {
                $data['nickname'] = $param['nickname'];
            }
            validate(ValidateUser::class)->scene('account')->check($data);
            $res = User::where(['id' => $this->uid])->update($data);
            if ($res) {
                $recordLog(1, ['original_data' => $user]);
                return success();
            }
            return error();
        } catch (Validate $e) {
            $recordLog(0, $e->getMessage());
            return error($e->getMessage());
        }
    }
    public function uploadAvator()
    {
        $file =  request()->file();
        
        try {
            validate(['file' => 'fileSize:5242880|fileExt:jpg,png,jpeg'])
                ->check($file);
            if (empty($file)) return error();
            $has = Db::name('avator')->where(['user_id' => $this->uid])->find();
            $avator = \think\facade\Filesystem::disk('images')->putFile('avator', $file['file']);
            if (!$avator) return error('头像上传失败');
            $avator = '/static/images/' . str_replace('\\', '/', $avator);
            Db::name('files')->insert([
                'user_id' => $this->uid,
                'desc' => '头像上传',
                'route_path' => request()->controller() . '/' . request()->action(),
                'file_name' => $file['file']->getFilename(),
                'file_path' => $avator,
                'size' => $file['file']->getSize(),
                'create_time' => time()
            ]);
            if ($has && $has['avator']) {
                $res = Db::name('avator')->where(['user_id' => $this->uid])->update(['avator' => $avator, 'create_time' => time()]);
            } else {
                $res = Db::name('avator')->insert(['user_id' => $this->uid, 'avator' => $avator, 'create_time' => time()]);
            }
            if ($res) {
                LogService::record(
                    user_id: $this->uid,
                    name: '上传头像',
                    content: ['original_data' =>  $has]
                );
                return success(addHost($avator));
            }
            return error();
        } catch (\think\exception\ValidateException $e) {
            return error($e->getMessage());
        }
    }
    public function changePassword()
    {
        $oldPassword = input('oldPassword');
        $newPassword = input('newPassword');
        if (empty($oldPassword) || empty($newPassword)) return error('参数错误', 201);
        $recordLog = function ($status, $message = '') {
            LogService::record(
                name: '修改密码',
                user_id: $this->uid,
                status: $status,
                content: $message == '' ? [] : $message,
            );
        };
        try {
            // 验证新密码格式
            validate(['password|新密码' => 'require|min:5|max:11|alphaNum'])->check(['password' => $newPassword]);

            // 获取用户信息
            $user = User::where(['id' => $this->uid])->find();
            if (!$user) {
                $recordLog(0, ['reason' => '用户不存在']);
                return error('用户不存在');
            }

            // 验证旧密码
            if (encrypt_pwd($oldPassword) != $user['password']) {
                $recordLog(0, ['reason' => '旧密码错误']);
                return error('旧密码错误');
            }

            // 验证新旧密码不能相同
            if (encrypt_pwd($oldPassword) == encrypt_pwd($newPassword)) {
                $recordLog(0, ['reason' => '旧密码不能与新密码一样']);
                return error('旧密码不能与新密码一样');
            }

            // 更新密码
            $res = User::where(['id' => $this->uid])->update(['password' => encrypt_pwd($newPassword)]);
            if ($res) {
                $recordLog(1, ['original_data' => $user]);
                return success();
            }
            return error();
        } catch (ValidateException $e) {
            return error($e->getError());
        }
    }
    // 积分明细
    public function getScoreLog()
    {
        return success(ScoreLog::getUserLogs($this->uid));
    }
    // 查看别人主页
    public function info($id)
    {
        $user = User::where(['id' =>  $id])
            ->field('id,nickname,score,exp,role,signature,avator,last_login_ip,last_time,create_time')
            ->hidden(['last_login_ip'])->find();
        if (!$user) return error('用户不存在');
        // is_friend
        $hasFollow = Db::name('follow')->where(['user_id' => $this->uid, 'follow_id' => $id, 'relation_type' => 1, 'delete_time' => 0])->find();
        $user['is_followed'] = $hasFollow ? 1 : 0;
        $user['is_friend'] = Follow::checkIsFriend($id) ? 1 : 0;
        $user['art'] = Article::where(['user_id' => $id])->count();
        $user['comment'] = Comment::where(['user_id' => $id])->count();
        $user['collect'] = ArtCollect::where(['user_id' => $id])->count();
        $user['follow'] = Db::name('follow')->where(['user_id' => $id, 'relation_type' => 1, 'delete_time' => 0])->count();
        $user['fans'] = Db::name('follow')->where(['follow_id' => $id, 'relation_type' => 1, 'delete_time' => 0])->count();
        $user['is_vip'] = User::checkVip($id);
        LogService::record(
            user_id: getUid(),
            name: '查看主页',
            target_id: $id
        );
        return success($user);
    }
}
